package com.yilin.tms.core.commons.utils;

import com.google.gson.reflect.TypeToken;
import com.yilin.commons.exception.BusinessException;
import com.yilin.commons.util.ArrayUtil;
import com.yilin.commons.util.GpsMapUtil;
import com.yilin.commons.util.JsonUtil;
import com.yilin.tms.core.components.redis.RedisClient;
import com.yilin.tms.core.components.redis.RedisKeys;
import com.yilin.tms.core.entity.order.dispatch.DispatchOrderNote;
import com.yilin.tms.core.entity.order.goods.GoodsOrder;
import com.yilin.tms.core.entity.order.goods.GoodsOrderNote;
import com.yilin.tms.core.entity.order.rob.RobOrderNote;
import com.yilin.tms.core.entity.order.transit.TransitOrder;
import com.yilin.tms.core.entity.order.transit.TransitOrderNote;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderUtil {


    //根据结算方式获取相应费用
    //真实运输费用
    public static Double getTransCostBySettleType(GoodsOrder.SettlementType settlementType, TransitOrder transitOrder){
        switch (settlementType){
            case releasePricing:
                return transitOrder.getPricingTransportCost();
            case assignWav:
                return transitOrder.getAssignTransportCost();
            case loadingWav:
                return transitOrder.getLoadingTransportCost();
            case deliverWav:
                return transitOrder.getDeliverTransportCost();
            case arriveWav:
                return transitOrder.getReceiptTransportCost();
            case gatherTotal:
                return transitOrder.getGatherTransportCost();
            default: return 0D;
        }
    }

    //生成标题
    public static String genOrderTitle(DispatchOrderNote first){
        return genOrderTitle(first.getConsignorArea(),first.getConsigneeArea());
    }
    //生成标题
    public static String genOrderTitle(GoodsOrderNote first){
        return genOrderTitle(first.getConsignorArea(),first.getConsigneeArea());
    }
    //生成标题
    public static String genOrderTitle(RobOrderNote first){
        return genOrderTitle(first.getConsignorArea(),first.getConsigneeArea());
    }
    //生成标题
    public static String genOrderTitle(TransitOrderNote first){
        return genOrderTitle(first.getConsignorArea(),first.getConsigneeArea());
    }

    private static String genOrderTitle(String consignorArea,String consigneeArea){
        String[] starts = consignorArea.split("-");
        String[] ends = consigneeArea.split("-");
        String start = starts[1] + "-" + starts[2];
        String end = ends[1] + "-" + ends[2];
        return String.format("%s → %s", start, end);
    }

    /**
     * 推送相关
     * */
    public static void verifySaveGoodsPush(String pushKey){
        //定义redis的key
        RedisClient redisClient = RedisClient.getInstance();
        //单货源每日限制推送5次
        String countStr = redisClient.hget(RedisKeys.ORDER_GOODS_PUSH, pushKey);
        if (countStr == null) countStr = "{}";
        Map<String,Object> map = JsonUtil.jsonToObject(countStr,new TypeToken<Map<String,Object>>(){});
        if (!map.containsKey("pushCount")) map.put("pushCount",0);
        int count = (int) map.get("pushCount");
        if (count > 15)  throw new BusinessException("您今日货源推送次数已用完");
        if (map.containsKey("pushTime")) {
            long time = (Long) map.get("pushTime");
            long elapseTime = System.currentTimeMillis() - time; //60
            if (elapseTime / 1000 < 10 * 60) {
                long surplus = 10 * 60 - elapseTime / 1000;
                throw new BusinessException(String.format("您的推送太频繁了，请%s后再试", surplus));
            }
        }
        map.put("pushCount", count + 1);
        map.put("pushTime", System.currentTimeMillis());
        redisClient.hset(RedisKeys.ORDER_GOODS_PUSH, pushKey,JsonUtil.objectToJson(map));
    }

    // 获取所有保存的推送KEY
    public static Map<String, Long> getAllGoodsPushMapTime() {
        Map<Object, Object> map = RedisClient.getInstance().hEntries(RedisKeys.ORDER_GOODS_PUSH);
        Map<String,Long> accessMap = new HashMap<>();
        for (Object key : map.keySet()){
            if (map.get(key)==null) continue;
            Map<String, Object> codeMap = JsonUtil.jsonToObject(map.get(key).toString(), new TypeToken<Map<String, Object>>() {});
            accessMap.put(key.toString(),(long) codeMap.get("pushTime"));
        }
        return accessMap;
    }

    public static void removeSaveGoodsPush(String fieldKey) {
        RedisClient redisClient = RedisClient.getInstance();
        redisClient.hdel(RedisKeys.ORDER_GOODS_PUSH,fieldKey);
    }

    // 坐标三元排序 发货点
    public static List<TransitOrderNote> sortORLatLngList(List<TransitOrderNote> allPointList, String truckLngLat) {
        if (truckLngLat==null) return allPointList;
        return ArrayUtil.sortPoTList(truckLngLat, allPointList, new ArrayList<>(), (p, a, b) -> {
            double v = GpsMapUtil.getDistance(p, a.getConsignorCoordinate()) - GpsMapUtil.getDistance(p, b.getConsignorCoordinate());
            return v > 0 ? 1 : (v < 0 ? -1 : 0);
        }, TransitOrderNote::getConsignorCoordinate);
    }

    // 坐标三元排序 收货点
    public static List<TransitOrderNote> sortEELatLngList(List<TransitOrderNote> allPointList, String truckLngLat) {
        if (truckLngLat==null) return allPointList;
        return ArrayUtil.sortPoTList(truckLngLat, allPointList, new ArrayList<>(), (p, a, b) -> {
            double v = GpsMapUtil.getDistance(p, a.getConsigneeCoordinate()) - GpsMapUtil.getDistance(p, b.getConsigneeCoordinate());
            return v > 0 ? 1 : (v < 0 ? -1 : 0);
        }, TransitOrderNote::getConsigneeCoordinate);
    }
}

